package com.dlxy.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dlxy.model.domain.User;
import com.dlxy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    private List<Long> mainUserList = Arrays.asList(-1L,1L);

    @Scheduled(cron = "0 24 16 * * *")
    public void doCacheRecommendUser() {

        RLock rLock = redissonClient.getLock("partner:PreCacheJob:doCacheRecommendUser:lock");


        try {
            if (rLock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                for (long userId :mainUserList) {
                    QueryWrapper queryWrapper=new QueryWrapper();
                    Page<User> page = userService.page(new Page<>(1, 8), queryWrapper);

                    String redisKey = String.format("partner:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

                    try {
                        valueOperations.set(redisKey,page,30000,TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error",e);
                    }

                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser  fail",e);
        }finally {
            if (rLock.isHeldByCurrentThread()){
                rLock.unlock();
            }
        }


    }
}
